﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PIM_ATE.Electrical;
using System.Threading;

namespace PIM_ATE
{
    partial class FrmCalConfirmPim : Form
    {
        InstrumentGroup m_groupType;
        ClsCalInstrumentsInfoBuilder m_InstrumentsInfoBuilder;
        ClsCalInstrumentsInfo m_InstrumentsInfo;
        ClsDataUser m_usrObj;
        JcPIMInstrumentInfo[] m_lstInstrument;
        List<ClsDataConfigLocal> m_lstConfig;
        PIMProcess m_processObj;
        DataTable m_pim_dtShow;
        float m_plot_x_start = 0;
        float m_plot_y_start = 0;
        //Dictionary<int, JcPIMDataMaxResult> m_dicResults;
        ClsCalRecord m_CalRecord;
        List<ClsCalRecordItem> m_CalRecordItemList;

        public FrmCalConfirmPim(JcPIMInstrumentInfo[] infos, InstrumentGroup groupType, ClsDataUser user)
        {
            InitializeComponent();
            m_InstrumentsInfoBuilder = new ClsCalInstrumentsInfoBuilder(GDefine.DBNamePIM);
            m_InstrumentsInfo = new ClsCalInstrumentsInfo();
            m_lstConfig = new List<ClsDataConfigLocal>();
            m_processObj = new PIMProcessForAntenna(this, infos, groupType, null, null);
            m_groupType = groupType;
            m_usrObj = user;
            m_lstInstrument = infos;
            cbTestType.SelectedIndex = 0;


            ctl_pim_dgvData.BackgroundColor = SystemColors.Control;
            //   ctl_pim_dgvData.Dock = DockStyle.Fill;
            ctl_pim_dgvData.RowHeadersVisible = false;
            ctl_pim_dgvData.AllowUserToAddRows = false;
            ctl_pim_dgvData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            ctl_pim_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            ctl_pim_dgvData.ReadOnly = true;
            ctl_pim_dgvData.MultiSelect = false;

            m_processObj.evt_set_settings_handle += m_process_evt_set_settings_handle;
            m_processObj.evt_get_results_handle += m_process_evt_get_results_handle;
            m_processObj.evt_complete_process_handle += m_process_evt_complete_process_handle;
            m_processObj.evt_complete_all_process_handle += m_process_evt_complete_all_process_handle;
            m_processObj.evt_log_handle += m_process_evt_log_handle;

            creatCheckRecord(true);
        }

        #region event
        void m_process_evt_log_handle(object sender, EventArgs e)
        {

        }

        void m_process_evt_complete_all_process_handle(object sender, EventArgs e)
        {
            this.Invoke(new ThreadStart(delegate
            {
                setEnable(true);
                if (sender != null)
                {
                    MessageBox.Show(sender as string);
                }
                ctl_pim_dgvData.ClearSelection();
            }));
        }

        void m_process_evt_complete_process_handle(object sender, EventArgs e)
        {
            EventProcessArgs eProcess = e as EventProcessArgs;
            float fMax = (float)eProcess.processObj;
            bool bResult = eProcess.processState;
            this.Invoke(new ThreadStart(delegate
            {
                DataTable table = m_pim_dtShow;
                DataGridView dgv = ctl_pim_dgvData;

                table.Rows[eProcess.processNum]["测试最大值"] = fMax;

                if (bResult)
                {
                    table.Rows[eProcess.processNum]["判定结果"] = GDefine.ContentFail;
                    dgv.Rows[eProcess.processNum].Cells["判定结果"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                    dgv.Rows[eProcess.processNum].Cells["测试最大值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                    dgv.Rows[eProcess.processNum].Cells["实时测试值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                }
                else
                {
                    table.Rows[eProcess.processNum]["判定结果"] = GDefine.ContentPass;
                    dgv.Rows[eProcess.processNum].Cells["判定结果"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                    dgv.Rows[eProcess.processNum].Cells["测试最大值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                    dgv.Rows[eProcess.processNum].Cells["实时测试值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                }
            }));
        }

        void m_process_evt_set_settings_handle(object sender, EventArgs e)
        {
            JcPIMDataSettings settings = sender as JcPIMDataSettings;
            EventProcessArgs ePorcess = e as EventProcessArgs;
            this.Invoke(new ThreadStart(delegate
            {
                DataGridView dgv = ctl_pim_dgvData;
                if (ePorcess.processNum >= 0 && ePorcess.processNum < dgv.Rows.Count)
                {
                    dgv.Rows[ePorcess.processNum].Selected = true;
                    int n = (dgv.Height - dgv.ColumnHeadersHeight) / dgv.RowTemplate.Height - 1;
                    if (ePorcess.processNum > n)
                    {
                        if (dgv.Rows[ePorcess.processNum - n].Visible)
                            dgv.FirstDisplayedScrollingRowIndex = ePorcess.processNum - n;
                        else
                            dgv.FirstDisplayedScrollingRowIndex = ePorcess.processNum;
                    }
                    else
                    {
                        if (dgv.Rows[0].Visible)
                            dgv.FirstDisplayedScrollingRowIndex = 0;
                        else
                            dgv.FirstDisplayedScrollingRowIndex = ePorcess.processNum;
                    }

                    m_pim_dtShow.Rows[ePorcess.processNum]["测试最大值"] = "";
                    m_pim_dtShow.Rows[ePorcess.processNum]["判定结果"] = "";
                    m_pim_dtShow.Rows[ePorcess.processNum]["实时测试值"] = "";
                }

                CurveChart plot = ctl_pim_ccPlot;
                plot.Clear();
                if (settings.Mode == ImMode.Freq)
                {
                    plot.SetPlotTitle("扫频模式", "MHz", "");
                    if (settings.RXs != settings.RXe)
                        plot.SetPlotX((float)settings.RXs, (float)settings.RXe);
                }
                else
                {
                    plot.SetPlotTitle("点频模式", "", "");
                    plot.SetPlotX(0, settings.Time);
                    m_plot_x_start = 0;
                    m_plot_y_start = settings.Time + 10;
                }
            }));
        }

        void m_process_evt_get_results_handle(object sender, EventArgs e)
        {
            JcPIMDataResults val = sender as JcPIMDataResults;
            EventProcessArgs ePorcess = e as EventProcessArgs;
            int n = val.No;
            float p1 = val.P1;
            float f1 = val.F1;
            float p2 = val.P2;
            float f2 = val.F2;
            float im_f = val.Im_F;
            float im_v = val.Im_V;
            int n1 = val.n1;
            int n2 = val.n2;

            this.Invoke(new ThreadStart(delegate
            {
                CurveChart plot = ctl_pim_ccPlot;
                DataTable table = m_pim_dtShow;

                if (n1 == 0 && n2 == 0)
                {
                    plot.Add(new PointF(n, im_v), 0);
                    if (n >= m_plot_y_start)
                        m_plot_y_start += 10;
                    plot.SetPlotX(m_plot_x_start, m_plot_y_start);
                }
                else if (n <= n1)
                {
                    plot.Add(new PointF(im_f, im_v), 0);
                }
                else
                {
                    plot.Add(new PointF(im_f, im_v), 1);
                }

                ctl_pim_lblPower.Text = "P1=" + p1 + " | P2=" + p2;
                table.Rows[ePorcess.processNum]["实时测试值"] = im_v;
            }));
        }
        #endregion

        private void cb_InsturmentBand_SelectedIndexChanged(object sender, EventArgs e)
        {
            string instrAddress = "";
            List<string> lstIDN = new List<string>();
            for (int i = 0; i < m_lstInstrument.Length; i++)
            {
                if (m_lstInstrument[i].instrBandAlias == cb_InsturmentBand.Text)
                {
                    if (m_lstInstrument[i].instrEnable == false)
                    {
                        MessageBox.Show("该频段仪表未勾选,不可用！", "错误");
                        return;
                    }
                    instrAddress = m_lstInstrument[i].instrAddress;
                    break;
                }
                if (i == m_lstInstrument.Length)
                {
                    MessageBox.Show("未查找到可用仪表！", "错误");
                    return;
                }
            }

            if (m_groupType == InstrumentGroup.DESKTOP || m_groupType == InstrumentGroup.RFDESKTOP)
            {
                if (instrAddress != "")
                {
                    lstIDN = m_InstrumentsInfoBuilder.getInstrumentIDByBandIp(cb_InsturmentBand.Text, instrAddress, true);

                }
                else
                {
                    MessageBox.Show("该频段仪表不存在，请重新进行设备配置", "错误");
                    return;
                }
            }
            else
            {
                lstIDN = m_InstrumentsInfoBuilder.getInstrumentIDByBandIp(cb_InsturmentBand.Text, null, false);
            }

            if (lstIDN != null)
            {
                if (lstIDN.Count != 1)
                {//仅提示
                    MessageBox.Show("该频段仪表注册IP地址重复，请选择需要校准的仪表(序列号)", "提示");
                }
                cb_InsturmentID.Items.Clear();
                for (int i = 0; i < lstIDN.Count; i++)
                {
                    cb_InsturmentID.Items.Add(lstIDN[i]);
                    cb_InsturmentID.Text = lstIDN[i];
                }
            }
            else
            {
                MessageBox.Show("该频段仪表未注册，请重新进行校准设备信息配置", "错误");
                return;
            }
        }

        private void cb_InsturmentID_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ClsCalInstrumentsInfo Info = m_InstrumentsInfoBuilder.getInstrumentInfoByInstrumentID(cb_InsturmentID.Text);
                txt_InsturmentIP.Text = Info.InstrumentIP;
                nud_InstrumentCalSpec.Value = Convert.ToDecimal(Info.InstrumentCalSpec);

                btn_set_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误");
            }
        }

        #region method
        List<ClsDataConfigLocal> download(out DataTable dtShow)
        {
            dtShow = null;
            getConfig();
            List<ClsDataConfigLocal> lstConfig = m_lstConfig;
            if (lstConfig == null) return null;
            dtShow = new DataTable();
            string[] colNames = getPIMColNames().ToArray();
            for (int i = 0; i < colNames.Length; i++)
            {
                dtShow.Columns.Add(colNames[i]);
            }
            for (int i = 0; i < lstConfig.Count; i++)
            {
                DataRow row = dtShow.NewRow();
                row[0] = lstConfig[i].PIMItemName;
                row[1] = lstConfig[i].BandAlias;
                row[2] = lstConfig[i].SpecReg;
                dtShow.Rows.Add(row);
            }
            return lstConfig;
        }
        void getConfig()
        {
            getInfo();
            int count = 0;
            if (m_groupType == InstrumentGroup.DESKTOP || m_groupType == InstrumentGroup.RFDESKTOP)
            {
                for (int i = 0; i < m_lstInstrument.Length; i++)
                {
                    if (m_lstInstrument[i].instrEnable == true && m_lstInstrument[i].instrBandAlias == cb_InsturmentBand.Text)
                    {
                        count = m_lstInstrument[i].instrPort; break;
                    }
                }
            }
            else
            {
                count = 2;
            }
            ClsDataConfigLocal[] lstConfig = new ClsDataConfigLocal[count];
            ClsCalRecordItem[] lstItem = new ClsCalRecordItem[count];
            for (int n = 0; n < lstConfig.Length; n++)
            {
                lstConfig[n] = new ClsDataConfigLocal();
                lstConfig[n].ID = n;
                lstConfig[n].Enable = true;
                lstConfig[n].ProCode = "";
                lstConfig[n].RetSpeed = 0;
                lstConfig[n].RCUIndex = "XX";
                lstConfig[n].TestAngle = 0;
                lstConfig[n].BandAlias = m_InstrumentsInfo.InstrumentBand;
                lstConfig[n].Message = "";
                lstConfig[n].SpecUnit = "dBm";
                lstConfig[n].IsKnock = false;
                lstConfig[n].PIMItemName = "P" + (n + 1);

                lstConfig[n].IsSweepTest = cbTestType.SelectedIndex == 0;
                lstConfig[n].PIMOrder = 3;
                lstConfig[n].SpecReg = m_InstrumentsInfo.InstrumentCalSpec;
                lstConfig[n].TX1L = 0;
                lstConfig[n].TX1H = 0;
                lstConfig[n].TX2L = 0;
                lstConfig[n].TX2H = 0;
                lstConfig[n].RXL = 0;
                lstConfig[n].RXH = 0;
                lstConfig[n].TestStep1 = 0;
                lstConfig[n].TestStep2 = 0;
                lstConfig[n].F1Freq = 0;
                lstConfig[n].F2Freq = 0;
                lstConfig[n].PIMFreq = 0;
                lstConfig[n].TestTime = Convert.ToInt32(txtTime.Text.Trim());
                lstConfig[n].F1Power = Convert.ToDouble(nudTx.Value);
                lstConfig[n].F2Power = Convert.ToDouble(nudTx.Value);
                lstConfig[n].PortTip = "";

                lstItem[n] = new ClsCalRecordItem();
                lstItem[n].Port = lstItem[n].PortIndex = lstConfig[n].PIMItemName;
                lstItem[n].Spec = "[-INF," + lstConfig[n].SpecReg + "]";
                lstItem[n].Band = lstConfig[n].BandAlias;
                lstItem[n].ValueType = "PIM";
            }
            m_lstConfig.Clear();
            m_lstConfig.AddRange(lstConfig);

            m_CalRecordItemList.Clear();
            m_CalRecordItemList.AddRange(lstItem);
            m_CalRecord.InstrumentID = m_InstrumentsInfo.InstrumentID;
        }
        void getInfo()
        {
            ClsCalInstrumentsInfo Info = new ClsCalInstrumentsInfo();
            Info.InstrumentBand = cb_InsturmentBand.Text;
            Info.InstrumentCalSpec = nud_InstrumentCalSpec.Value.ToString();
            Info.InstrumentIP = txt_InsturmentIP.Text.Trim();
            Info.InstrumentID = cb_InsturmentID.Text;
            m_InstrumentsInfo = Info;
        }
        List<string> getPIMColNames()
        {
            List<string> names = new List<string>();
            names.Add("测试项目");
            names.Add("测试频段");
            names.Add("测试要求");
            names.Add("测试最大值");
            names.Add("判定结果");
            names.Add("实时测试值");
            return names;
        }
        void setEnable(bool b)
        {
            groupBox2.Enabled = b;
            groupBox3.Enabled = b;
        }
        public int selectTips(string text)
        {
            int ret = 1;
            this.Invoke(new ThreadStart(delegate
            {
                FrmRetry frmTips = new FrmRetry(true);
                DialogResult dr = frmTips.ShowDialog();
                if (dr == DialogResult.No)
                {
                    ret = -1;
                }
                else if (dr == DialogResult.Retry)
                {
                    ret = 1;
                }
                else if (dr == DialogResult.Ignore)
                {
                    ret = 0;
                }
            }));
            return ret;
        }
        public bool Tips(string text, int btn = 1)
        {
            bool ret = false;
            this.Invoke(new ThreadStart(delegate
            {
                MessageBoxButtons msgBtn = btn == 1 ? MessageBoxButtons.OKCancel : MessageBoxButtons.OK;
                if (MessageBox.Show(text, "提示", msgBtn) == DialogResult.OK)
                {
                    ret = true;
                }
                else
                {
                    ret = false;
                }
            }));
            return ret;
        }

        void creatCheckRecord(bool isCreat = true)
        {
            if (isCreat)
            {             
                m_CalRecord = new ClsCalRecord();
                m_CalRecordItemList = new List<Electrical.ClsCalRecordItem>();

                m_CalRecord.PCIP = m_usrObj.sEquID;
                m_CalRecord.UserID = m_usrObj.sUser;
                m_CalRecord.UserID2 = m_usrObj.sUser2;
                m_CalRecord.ValueType = "交调";          
            }
            else
            {
                //m_CheckRecord = null;
                //m_lstCheckRecordItem = null;
            }
        }
        public void DataCalProcessUpload()
        {




            //Electrical.ClsDataCalResult CheckResult = new Electrical.ClsDataCalResult(GDefine.DBNameELEC);
            //if (CheckResult.updateRecord(m_CheckRecord, m_lstCheckRecordItem))
            //{
            //    MessageBox.Show("上传校准数据成功");
            //}
            //else
            //{
            //    MessageBox.Show("上传校准数据失败");
            //}


            //if (m_resultBuilder.upload(m_dicResults, m_lstConifg))
            //{
            //    On_evt_log_handle("resultData: 上传数据成功", null);
            //}
            //else
            //{
            //    On_evt_log_handle("resultData: 上传数据失败", null);
            //}
        }
        #endregion

        private void btn_start_Click(object sender, EventArgs e)
        {
            setEnable(false);       
            btn_set_Click(sender, e);
            if (m_CalRecord.InstrumentID == null || m_CalRecord.InstrumentID == "")
            {
                setEnable(true);    
                MessageBox.Show("未选择校准仪表");
                return;
            }
            ClsDataProduct productObj = new ClsDataProduct();
            productObj.enableConfig = new List<bool>();
            for (int i = 0; i < m_lstConfig.Count; i++)
            {
                productObj.enableConfig.Add(true);
            }
            m_processObj.PIMProcessCalibration(m_lstConfig, productObj, m_usrObj,m_CalRecord,m_CalRecordItemList);
        }

        private void btn_set_Click(object sender, EventArgs e)
        {
            m_pim_dtShow = new DataTable();
            download(out  m_pim_dtShow);
            ctl_pim_dgvData.DataSource = m_pim_dtShow.DefaultView;
            ctl_pim_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            for (int i = 0; i < ctl_pim_dgvData.Columns.Count; i++)
            {
                ctl_pim_dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

    }
}
